package com.appkubes.fintech.restful.application.file.service.impl;

import com.appkubes.fintech.core.po.FintechUserPersonalWithBLOBs;
import com.appkubes.fintech.restful.application.file.dao.IDCardDao;
import com.appkubes.fintech.restful.application.file.entity.IDCardVO;
import com.appkubes.fintech.restful.application.file.service.FileService;
import com.appkubes.fintech.restful.application.user.domain.UserCertificateDomain;
import com.appkubes.storage.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Resource
    IDCardDao idCardDao;
    @Resource
    UserCertificateDomain certificateDomain;

    @Resource
    StorageService storageService;

    @Value("${idcard.image.base.path}")
    String imagePath;

    @Override
    public Integer uploadIdCard(MultipartFile file, IDCardVO idCardVO) {
        Integer effectRows = 0;

        List<String> fileList = storageService.save(file, imagePath);

        if (fileList.size() == 0) {
            return 0;
        }

        log.info("上传路径: ", fileList.get(0));
        FintechUserPersonalWithBLOBs userPersonal = idCardDao.selectByPrimaryKey(idCardVO.getUserKey());
        if (userPersonal == null) {
            userPersonal = new FintechUserPersonalWithBLOBs();
            BeanUtils.copyProperties(idCardVO, userPersonal);
            idCardDao.insertSelective(userPersonal);
        }

        if ("front".equalsIgnoreCase(idCardVO.getViewType())) {
            userPersonal.setIdcardFrontView(fileList.get(0));

        }
        if ("back".equalsIgnoreCase(idCardVO.getViewType())) {
            userPersonal.setIdcardBackView(fileList.get(0));
        }
        effectRows += idCardDao.updateByPrimaryKey(userPersonal);
        //更新实名认证
        certificateDomain.updatePersonalCertificate(idCardVO.getUserKey(), 1);

        return effectRows;
    }
}
